package clue

import (
	"context"
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/common/http_client"
	"git.mycaigou.com/gfyx/common/simplecopier"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto"
	reportDto "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/oppty/report"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/repository/business_opportunity"
	contract3 "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/repository/common"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils/ossfile"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
	"strings"
)

type ReportService struct {
	reportRepository business_opportunity.ReportRepositoryIface
	commonRepo       contract3.CommonReposIface
}

func NewReportService(reportRepository business_opportunity.ReportRepositoryIface,
	commonRepo contract3.CommonReposIface) ReportServiceIface {
	return &ReportService{
		reportRepository: reportRepository,
		commonRepo:       commonRepo,
	}
}

func (s *ReportService) SearchContacts(ctx context.Context, condition *reportDto.ReportOptionRequest) (*http_client.BigDataResponse, error) {
	request := &reportDto.SearchContactRequest{
		PageNum:  condition.Page,
		PageSize: condition.PageSize,
		Keyword:  condition.Keyword,
	}

	if condition.ClueSource == "WINBID" {
		// 中标时，取开发商和供应商
		request.DeveloperOrganizingCode = condition.OrganizingCode
	} else if condition.ClueSource == "SUPPLIER" {
		// 工程单位时，取工程单位联系方式
		request.SupplierOrganizingCode = condition.OrganizingCode
	} else {
		// 其它时候，取开发商联系方式
		request.DeveloperOrganizingCode = condition.OrganizingCode
		request.CompanyCategory = "开发商"
	}

	return s.reportRepository.SearchContacts(ctx, request)
}

// Save 保存报备信息
func (s *ReportService) Save(ctx context.Context, params map[string]interface{}) (bool, error) {
	flag, err := s.reportRepository.Save(ctx, params)
	if err != nil {
		return false, err
	}
	return flag, nil
}

// GetReportSourceInfo 报备来源的附带信息
func (s *ReportService) GetReportSourceInfo(ctx context.Context, sourceType, sourceId string) (map[string]interface{}, error) {
	if sourceType == "CLUE" || sourceType == "" {
		data, err := s.reportRepository.GetReportSourceInfo(ctx, sourceType, sourceId)
		if err != nil {
			return nil, err
		}
		return data, nil
	} else {
		res := map[string]interface{}{}
		params := &reportDto.FillReportFormRequest{
			ClueSource:   sourceType,
			ClueSourceId: sourceId,
		}
		data, err := s.commonRepo.FillReportForm(ctx, params)
		if err != nil {
			return res, err
		}
		if len(data.Data) <= 0 {
			err := ykerrcode.TogRPCError(errcode.COMMON_DATA_NOT_EXIST, "找不到相应数据")
			stark.Logger.Warnf(ctx, "%s %s 找不到相应数据", params.ClueSource, params.ClueSourceId)
			return res, err
		}
		rs := data.Data[0]
		rs["submitter_company"] = authorize.GetTenantName(ctx)
		rs["submitter"] = authorize.GetUserName(ctx)
		rs["submitter_tel"] = authorize.GetMobilePhone(ctx)
		return rs, nil
	}
}

// GetMyReportList 获取我的线索
func (s *ReportService) GetMyReportList(ctx context.Context, requestDto *dto.ReportMyListRequestDto) (*dto.ReportMyListResponseDto, error) {
	result := dto.ReportMyListResponseDto{
		List: []dto.ReportListItem{},
	}
	remoteRes, err := s.reportRepository.GetReportList(ctx, requestDto)
	if err != nil {
		return nil, err
	}
	result.Page = requestDto.Page
	result.PageSize = requestDto.PageSize
	result.Total = int(remoteRes.Total)

	if remoteRes.List != nil {
		for _, item := range remoteRes.List {
			result.List = append(result.List, dto.ReportListItem{
				UID:                   item.Uid,
				ProjectTitle:          item.ProjectTitle,
				FollowStatus:          int(item.FollowStatus),
				Submitter:             item.Submitter,
				CompanyName:           item.CompanyName,
				ResponsiblePersonName: item.ResponsiblePersonName,
				ResponsiblePersonGUID: item.ResponsiblePersonGuid,
				AgencyName:            item.AgencyName,
				AgencyContact:         item.AgencyContact,
				CreatedOn:             item.CreatedOn,
				ModifiedOn:            item.ModifiedOn,
			})
		}
	}

	return &result, nil
}

func (s *ReportService) GetRegionReportList(ctx context.Context, requestDto *dto.ReportMyListRequestDto) (*dto.ReportMyListResponseDto, error) {
	result := dto.ReportMyListResponseDto{
		List: []dto.ReportListItem{},
	}
	if requestDto.SubmitStartTime != "" && requestDto.SubmitEndTime != "" {
		requestDto.SubmitStartTime = requestDto.SubmitStartTime + " 00:00:00"
		requestDto.SubmitEndTime = requestDto.SubmitEndTime + " 23:59:59"
	}
	remoteRes, err := s.reportRepository.GetRegionReportList(ctx, requestDto)
	if err != nil {
		return nil, err
	}
	result.Page = requestDto.Page
	result.PageSize = requestDto.PageSize
	result.Total = int(remoteRes.Total)

	if remoteRes.List != nil {
		for _, item := range remoteRes.List {
			result.List = append(result.List, dto.ReportListItem{
				UID:                   item.Uid,
				ProjectTitle:          item.ProjectTitle,
				FollowStatus:          int(item.FollowStatus),
				Submitter:             item.Submitter,
				CompanyName:           item.CompanyName,
				ResponsiblePersonName: item.ResponsiblePersonName,
				ResponsiblePersonGUID: item.ResponsiblePersonGuid,
				AgencyName:            item.AgencyName,
				AgencyContact:         item.AgencyContact,
				CreatedOn:             item.CreatedOn,
				ModifiedOn:            item.ModifiedOn,
			})
		}
	}

	return &result, nil
}

func (s *ReportService) GetReport(ctx context.Context, reportId string) (map[string]interface{}, error) {
	report, err := s.reportRepository.GetReport(ctx, reportId)
	if err != nil {
		return nil, err
	}
	data, _ := simplecopier.StructToMapByJsonTag(report)

	// 图片转成oss链接
	if value, ok := data["project_image"]; ok {
		imageList := make([]string, 0)
		if image, ok := value.(string); ok && image != "" {
			images := strings.Split(image, ",")
			for _, item := range images {
				url, err := ossfile.GetSignURL(item)
				if err != nil {
					stark.Logger.Errorf(ctx, "ossfile.GetSignURL err: %s | item: %s", err, item)
					continue
				}
				imageList = append(imageList, url)
			}
		}
		data["project_image"] = imageList
	}

	return data, nil
}

func (s *ReportService) GetTeamLeader(ctx context.Context, reportId string) (map[string]interface{}, error) {
	result, err := s.reportRepository.GetTeamLeader(ctx, reportId)
	if err != nil {
		return nil, err
	}
	return result, nil
}

func (s *ReportService) GetReportUserList(ctx context.Context) (map[string]interface{}, error) {
	//TODO implement me
	list, err := s.reportRepository.GetUserList(ctx)
	if err != nil {
		return nil, err
	}
	return list, nil
}
